<template>
  <div class="page-controller">
    <FISearchForm
      class="box-radius2"
      ref="ruleFormRef"
      :id="`inqu_${tableId}`"
      v-model:form-value="state.query"
      :table-column="columns"
      :wrapperSpan="searchWrapperSpan"
      :exclude-values="['userCName', 'groupCname', 'endTime']"
      @submit="searchFn"
      @reset="resetFn"
    >
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem class="date-range-class" prop="startTime" label="流程开始时间">
          <FIDatePicker
            value-format="YYYYMMDD"
            v-model="state.query.startTime"
            type="date"
            placeholder="流程开始时间"
            clearable
          />
          <FIDatePicker
            value-format="YYYYMMDD"
            v-model="state.query.endTime"
            type="date"
            placeholder="流程开始时间"
            clearable
          />
        </FIFormItem>
      </el-col>
      <!-- <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="endTime" label="至">
          <FIDatePicker
            value-format="YYYY-MM-DD"
            v-model="state.query.endTime"
            type="date"
            placeholder="流程开始时间"
            clearable
          />
        </FIFormItem>
      </el-col> -->
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="startId" label="流程发起人">
          <FIAutoInput
            v-model="state.query.userCName"
            :options="userList"
            value-key="userCName"
            :display-key="['loginName', 'userCName']"
            @select="selectClick($event, 'fqr')"
            @change="changeEvent($event, 'fqr')"
          >
            <template #default="{ item }">
              <div>{{ item.loginName }} {{ item.userCName }}</div>
            </template>
          </FIAutoInput>
        </FIFormItem>
      </el-col>
      <el-col :span="searchWrapperSpan" class="flex-center">
        <FIFormItem prop="startDeptId" label="发起部门">
          <!-- <FIAutoInput
                  v-model="state.query.groupCname"
                  :options="deptList"
                  value-key="groupCname"
                  :display-key="['groupEname','groupCname']"
                  @select="selectClick($event,'fq_dept')"
                  @change="changeEvent($event,'fq_dept')"
                  >
                  <template #default="{ item }">
                      <div>{{ item.groupCname }}</div>
                  </template>
              </FIAutoInput> -->
          <DeptTree v-model="state.query.startDeptId" />
        </FIFormItem>
      </el-col>
    </FISearchForm>
    <div class="margin-bottom20"></div>
    <FITable
      ref="tableRef"
      class="box-radius2"
      title="流程平均时效记录集"
      :id="`result_${tableId}`"
      :readonly="false"
      :data="state.dataList"
      primaryKey="id"
      :rowNo="true"
      v-model:columns="columns"
      :insertable="false"
      :isLoading="isTableLoading"
      :saveSuccessful="saveSuccessful"
      :pageConfig="pageConfig"
      @row-add-save="addRowSave"
      @table-refresh="searchFn"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-page-change="handleCurrentChange"
      @action-click="actionClick"
    >
      <template #headerBtn>
        <!-- <FIButton @click="menuShow = true" border style="margin-right:10px;">新增</FIButton> -->
        <FIButton id="export" border @click="exportClick"></FIButton>
      </template>
    </FITable>
  </div>
</template>
<script lang="ts" setup>
import { reactive, onMounted, ref, computed, watch } from 'vue'
import FISearchForm from '@/components/FISearchForm.vue'
import FIFormItem from '@/components/FIFormItem.vue'
import FIInput from '@/components/FIInput.vue'
import FIButton from '@/components/FIButton.vue'
import FIPopconfirmBtn from '@/components/FIPopconfirmBtn.vue'
import FITable from '@/components/FITable/index.vue'
import FISelect from '@/components/FISelect/index.vue'
import DeptTree from '../../components/DeptTree'
import { apiRequestPost } from '@/api/globalApi.js'
import { ElMessage } from 'element-plus'
import { useMessage, useMessageBox } from '@/hooks/message'
import type { PageConfig, Column } from '@/types/components'
import { useRoute } from 'vue-router'
import { initSearchData } from '@/utils/common'
import { getQueryTableCache } from '@/utils/cacheUtils'
import { apiQueryAvg, apieEportAvg, apiQueryUser, apiQueryDept } from '@/api/modules/EW.js'
const route = useRoute()
const menuShow = ref(false)
const searchWrapperSpan = 8
const showSearch = ref(true)
const isTableLoading = ref(false)
// 页面编码
const tableId = 'usersAudit'
// 保存成功按钮状态，默认不展示底部保存，取消按钮
const saveSuccessful = ref(false)
const tableRef = ref(null)
const userList = ref([])
const deptList = ref([])
const state = reactive({
  query: {
    startTime: '',
    endTime: '',
    startDeptId: '',
    startId: '',
    current: 1,
    size: 10,
    userCName: '',
    groupCname: '',
  },
  dataList: [],
})
const pageConfig: PageConfig = reactive({
  total: 0,
  currentPage: 1,
})
const columns: Column[] = reactive([
  {
    label: '流程名称',
    prop: 'processName',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '流程实例数',
    prop: 'processInsNum',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '流程节点数',
    prop: 'processNodeNum',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  {
    label: '平均时长（天）',
    prop: 'avgDuration',
    align: 'center',
    editType: 'input', // 显示类型: input 文本类型，date: 日期，textArea, select:单选，multiSelect:多选,time:时间，Cascader：级联选择器，custome:自定义
  },
  // {
  //   label: '',
  //   prop: 'action',
  //   actionConfig: [{ id: 'isTop', type: 'top' }],
  // },
])

const checkedRows = ref([])
const treeVal = ref([])
const handleSelectionChange = (e) => {
  checkedRows.value = e
}
const handleSizeChange = (e) => {
  pageConfig.pageSize = e
  pageConfig.currentPage = 1
  searchFn()
}

//导出
const exportClick = () => {
  apieEportAvg(state.query)
}
const resetFn = () => {
  state.query.groupCname = ''
  state.query.userCName = ''
}
const changeEvent = (e, type) => {
  if (!e) {
    if (type == 'fq_dept') state.query.startDeptId = ''
    if (type == 'fqr') state.query.startId = ''
  }
}
const selectClick = (data, type) => {
  console.log(data, type, 'data123')
  if (type == 'fqr') {
    state.query.startId = data.loginName
  } else {
    state.query.startDeptId = data.groupEname
  }
}
//删除事件
const deleteRow = () => {
  if (!checkedRows.value.length) {
    useMessage().warning('请选择一条数据')
    return
  }
  let ids = []
  Array.isArray(checkedRows.value) &&
    checkedRows.value.forEach((item: any) => {
      if (item?.id) ids.push(item?.id)
    })
  isTableLoading.value = true
  apiDeleteAuth(ids)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        useMessage().success(res.data.message)
        searchFn()
      }
    })
    .catch((error: any) => {
      useMessage().error(error.data.message)
      isTableLoading.value = false
    })
}
//操作
const actionClick = (item, rowData, btnInfo) => {}
const handleCurrentChange = (e) => {
  pageConfig.currentPage = e
  searchFn('page')
}
const searchFn = (type?: string, columnsVal?: any) => {
  const obj = initSearchData(type, columnsVal, columns, state.query)
  state.query = obj.queryData
  columns.values = obj.columns
  if (type == 'page') {
    state.query.current = pageConfig.currentPage
  } else {
    pageConfig.currentPage = 1
    state.query.current = 1
  }
  if (!state.query.startTime) {
    useMessage().warning('请选择流程开始时间')
    return
  }
  isTableLoading.value = true
  if (pageConfig.pageSize) state.query.size = pageConfig.pageSize

  apiQueryAvg(state.query)
    .then((res) => {
      console.log(res, 'res')
      isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        // console.log(state.dataList)
        pageConfig.pageSize = Number(res.data.data.size)
        pageConfig.total = Number(res.data.data.count)
      } else {
        // ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
      // 处理错误
    })
}
const handleSave = () => {
  isTableLoading.value = true
  saveSuccessful.value = false
  apiRequestPost('/rm2/pageMaint/save', checkedRows.value)
    .then((res) => {
      isTableLoading.value = false
      if (res.data.success) {
        // saveSuccessful.value = true
        tableRef.value.clearSelection()
        searchFn()
      } else {
        ElMessage.error(res.data.message)
      }
    })
    .catch((error: any) => {
      isTableLoading.value = false
    })
}
//   const exportRow = () => {
//     apiGroupUserExport(state.query)
//   }
const ruleFormRef = ref(null)

const addRowSave = (data) => {
  handleSave()
}
const getQueryUser = () => {
  apiQueryUser()
    .then((res) => {
      console.log(res, 'res123456')
      if (res.data.success) {
        userList.value = res.data.data
      } else {
      }
    })
    .catch((error: any) => {})
}
const getQueryDept = () => {
  apiQueryDept()
    .then((res) => {
      console.log(res, 'res123456')
      if (res.data.success) {
        deptList.value = res.data.data
      } else {
      }
    })
    .catch((error: any) => {})
}
onMounted(() => {
  getQueryUser() //查询人员
  getQueryDept() //查询部门
  // 获取查询条件缓存
  const { cachedQuery, cachedColumns } = getQueryTableCache(route.path, tableId, state.query, columns.values)
  if (cachedQuery) state.query = cachedQuery
  if (columns) columns.values = cachedColumns
  // searchFn()//初始化不掉数据
})
</script>
<style lang="less" scoped>
.date-range-class {
  display: flex !important;
  ::v-deep(.el-form-item__content) {
    width: 220px !important;
    display: flex !important;
    justify-content: space-between !important;
    .el-input__prefix {
      display: none !important;
    }
    .el-input {
      width: 107px !important;
    }
  }
}
</style>
